import './common'

import http from 'axios'

const init = () => {
  $('.loading').addClass('show')
  http({
    method: 'GET',
    url: 'https://api.yizhanketang.cn/api/v1/todos'
  }).then(({data}) => {
    $('.list-group').empty()
    if (data.data.length === 0) {
      $('<li class="empty">暂无数据</li>').appendTo('.list-group')
    } else {
      data.data.map(item => {
        const { objectId, content } = item
        // console.log(item)
        $(`<li
          class="list-group-item"
          data-objectId="${objectId}"
        >
          ${content}
        </li>`).appendTo('.list-group')
      })
    }
  }).catch(e => {
    alert(e)
  }).finally(() => {
    $('.loading').removeClass('show')
  })
}


init()

$('.list-group').on('click', '.list-group-item', function () {
  // console.log($(this).data('objectid'))
  location.href = `show.html?objectid=${$(this).data('objectid')}`
})

$('.input-group-append').on('click', function () {
  if(!$('#task').val()) {
    $('.remind').show().html('内容不能为空')
    setTimeout(function () {
      $('.remind').hide()
    }, 3000)
  } else {
    http({
      method: 'POST',
      url: 'https://api.yizhanketang.cn/api/v1/todos',
      data: {
        content: $('#task').val()
      }
    }).then(res => {
      init()
      $('#task').val('')
    }).catch(() => {
      $('.remind').show().html('网络错误，请刷新重试')
      setTimeout(function () {
        $('.remind').hide()
      }, 3000)
    })
  }
})



